package com.example.teachmall4.controller;

import com.example.teachmall4.entity.Goods;
import com.example.teachmall4.entity.Users;
import com.example.teachmall4.service.GoodsService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class IndexController {
    @Autowired
    private GoodsService goodsService;
    // 定义每页显示的商品数量
    private static final int PAGE_SIZE = 6;

    @GetMapping("/")
    public String index(Model model, HttpSession session, @RequestParam(defaultValue = "1") int page) {
        // 检查用户是否已登录
        Users loginUser = (Users) session.getAttribute("loginUser");
        if (loginUser == null) {
            return "redirect:/user/login";
        }

        // 将登录用户信息添加到模型中
        model.addAttribute("loginUser", loginUser);

        // 获取总记录数
        long total = goodsService.count();
        // 计算总页数
        int totalPages = (int) Math.ceil((double) total / PAGE_SIZE);

        // 确保页码在有效范围内
        if (page < 1) {
            page = 1;
        }
        if (page > totalPages) {
            page = totalPages;
        }

        // 获取当前页的数据
        List<Goods> goodsList = goodsService.findByPage(page, PAGE_SIZE);

        // 将数据添加到模型中，以便在 JSP 页面中使用
        model.addAttribute("goodsList", goodsList);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("total", total);

        // 返回视图名称，Spring 会找到对应的 index.jsp
        return "index";
    }
}